﻿#include "dialog_manualfocus.h"
#include "ui_dialog_manualfocus.h"
#include <QDebug>

Dialog_ManualFocus::Dialog_ManualFocus(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog_ManualFocus)
{
    ui->setupUi(this);

    QList<double> levels;
    //levels << 0.003;
    levels << 0.01;
    levels << 0.03;
    levels << 0.1;
    levels << 0.3;
    levels << 1;
    levels << 3;
    levels << 10;
    //levels << 30;

    m_levels = levels;
    int num = m_levels.size();
    ui->verticalSlider->setMaximum(num - 1);
    ui->verticalSlider->setValue(num / 2);

    m_showImage = new showImage(ui->widget);

}

Dialog_ManualFocus::~Dialog_ManualFocus()
{
    delete ui;
}

void Dialog_ManualFocus::updateImage(const uint8_t *pBuf, QSize size)
{
    int imageWidth = size.width();
    int imageHeight = size.height();

    m_image_mutex.lock();
    if(m_image.size() != size)
    {
        m_image = QImage(size, QImage::Format_RGB888);
    }
    for (int row = 0; row < imageHeight; row++)
    {
        rgb24 *line = (rgb24 *)m_image.scanLine(row);
        // 找到 CCD 数据一行的开头位置，一个像素占3字节
        rgb24 * pixel = (rgb24 *) &pBuf[3 * row * imageWidth];
        for (int col = 0; col < imageWidth; col ++)
        {
            line[imageWidth - col - 1] = pixel[col];
        }
    }
//    flipImage(m_image, static_cast<FlipMode>(m_flip_mode));
    m_showImage->resize(imageWidth/2, imageHeight/2);
    m_showImage->showImg(m_image.scaled(imageWidth/2, imageHeight/2));
    m_image_mutex.unlock();

//    qDebug() << "updateImage";
//    ui->label->setPixmap(QPixmap::fromImage(m_image).scaled(ui->label->size()));


}

void Dialog_ManualFocus::on_pushButton_close_clicked()
{
    done(Rejected);
}

void Dialog_ManualFocus::on_pushButton_ok_clicked()
{
    done(Accepted);
}

void Dialog_ManualFocus::on_pushButton_moveUp_pressed()
{
    emit moveUp();
}

void Dialog_ManualFocus::on_pushButton_moveUp_released()
{
    emit stop();
}

void Dialog_ManualFocus::on_pushButton_moveDown_pressed()
{
    emit moveDown();
}

void Dialog_ManualFocus::on_pushButton_moveDown_released()
{
    emit stop();
}

void Dialog_ManualFocus::on_pushButton_stop_pressed()
{
    emit stop();
}

void Dialog_ManualFocus::on_verticalSlider_valueChanged(int value)
{

    double speed = m_levels.at(value);
    ui->label_speed->setText(QString("%1\nmm/s").arg(speed, 6, 'f', 3, ' '));
    qDebug() << "ZControlGroupBox changeSpeed = " << speed;
    emit changeSpeed(speed);
}

int Dialog_ManualFocus::getResult()
{
    return m_showImage->getResult();
}
